package pizza.admin.dao;

import java.util.Collection;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.NoResultException;
import javax.persistence.Persistence;
import javax.persistence.TypedQuery;

import pizza.admin.entity.OrderPizza;
import pizza.admin.entity.User;

public class OrderPizzaDAO implements OrderPizzaDAOInterface {

	private EntityManager em;

	public OrderPizzaDAO() {
		initializeEntityManager();
	}
	
	@Override
	public void initializeEntityManager() {
		// TODO Auto-generated method stub
		EntityManagerFactory entityFactory = Persistence
				.createEntityManagerFactory("PizzaPU");
		this.em = entityFactory.createEntityManager();

	}

	@Override
	public OrderPizza getById(Integer id) {
		OrderPizza orderPizza = null;
		orderPizza = em.find(OrderPizza.class, id);
		return orderPizza;
	}
	
	public OrderPizza getByOrderAndPizzaId(Integer pizzaId, Integer orderId){
		OrderPizza orderPizza = null;
		TypedQuery<OrderPizza> query = em.createQuery("SELECT op OrderPizza op WHERE pizzaId = :pizzaId AND orderId = :orderId", OrderPizza.class);
		query.setParameter("pizzaId", pizzaId).setParameter("orderId", orderId);
		try{
			orderPizza = query.getSingleResult();
			em.refresh(orderPizza);
			return orderPizza;
		} catch(NoResultException e){
			return null;
		}
	}

	@Override
	public void add(OrderPizza orderPizza) {
		try {
			em.getTransaction().begin();
			em.persist(orderPizza);
			em.getTransaction().commit();

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (em.getTransaction().isActive()) {
				em.getTransaction().rollback();
			}
		}
	}

	@Override
	public void edit(OrderPizza orderPizza) {
		try {
			em.getTransaction().begin();
			em.merge(orderPizza);
			em.getTransaction().commit();

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (em.getTransaction().isActive()) {
				em.getTransaction().rollback();
			}
		}
	}

	@Override
	public void delete(OrderPizza orderPizza) {
		// TODO Auto-generated method stub
		try {
			em.getTransaction().begin();
			em.remove(orderPizza);
			em.getTransaction().commit();

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (em.getTransaction().isActive()) {
				em.getTransaction().rollback();
			}
		}
	}
	
	public void destroy() {
		try {
			em.close();
		} catch (Exception ex) {
			System.out.println(ex.getMessage());
		}
	}

}
